"""
__author__ = 'loong'
"""
import os
import sys
import configparser
import argparse
from baye import datlib


DEFAULT_CONFIG = """
[output]
# 屏幕DPI放大倍数， 越大能显示越精细的图片
scale = 2
# 生成lib时目标引擎版本。0: 原版（老地址，词典）, 1: （alpha版）新地址
version = 1
"""


def lib2res(i, o, config):
    dat = open(i, 'rb').read()
    lib = datlib.Lib.parse_bin(dat, o, config=config)
    lib.decompile()


def res2lib(i, o, config):
    if config.output_version == 0:
        config.output_scale = 1
    lib = datlib.Lib.from_res(i, config)
    lib.compile(o)


def _main(filename=''):
    print('BayeCompiler v{}'.format(datlib.__version__))
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config', help="Config file", default='')
    parser.add_argument('filename', help='dat.res or dat.lib', nargs='?')
    args = parser.parse_args()

    filename = filename or args.filename
    if not filename:
        if len(sys.argv) == 2:
            filename = sys.argv[1]
        else:
            raise Exception(u'请将dat.res或dat.lib文件拖放到BayeCompiler.exe的图标上')
    if args.config:
        config_file = args.config
    else:
        basedir = os.path.dirname(sys.argv[0])
        config_file = os.path.join(basedir, "config.ini")

    if not os.path.exists(config_file):
        with open(config_file, 'w') as cf:
            cf.write(DEFAULT_CONFIG)

    config = datlib.Config()
    parser = configparser.ConfigParser()
    parser.read(config_file)
    if 'output' in parser:
        output = parser['output']
        config.output_scale = int(output.get('scale', config.output_scale))
        config.output_version = int(output.get('version', config.output_version))


    filename = os.path.abspath(os.path.expanduser(filename))

    if filename.endswith('.lib'):
        basename = filename.rsplit('.', 1)[0]
        lib2res(filename, '{}.res'.format(basename), config=config)
    elif filename.endswith('.res') and os.path.isdir(filename):
        basename = filename.rsplit('.', 1)[0]
        res2lib(filename, '{}-mod.lib'.format(basename), config=config)
    else:
        raise Exception('Unknown file type {}'.format(filename))


def main(filename=''):
    try:
        _main(filename=filename)
    except Exception as e:
        import traceback
        traceback.print_exc()
        print('错误:\n{}'.format(e))
        sys.stdin.read(1)
    else:
        from baye import util
        if util.has_warning:
            print('完成')
            sys.stdin.read(1)

if __name__ == '__main__':
    main()
